<template>
  <div class="app-container">
    <div class="filter-container">
      <!--设备使用状态  0 带待审核，激活  1正常   2禁用  3报修 4报废 -->
      <el-select v-model="listQuery.devType" class="filter-item" placeholder="型号" :clearable="true">
        <el-option
          v-for="(item,index) in devTypeList"
          :key="index"
          :label="item.itemValue"
          :value="item.itemKey"
        />
      </el-select>

      <el-select v-model="listQuery.online" class="filter-item" placeholder="在线状态" :clearable="true">
        <el-option label="在线" value="1" />
        <el-option label="离线" value="0" />
      </el-select>

      <el-select v-model="listQuery.devStatus" class="filter-item" placeholder="使用状态" :clearable="true">
        <el-option
          v-for="(item,index) in devStatusList"
          :key="index"
          :label="item.itemValue"
          :value="item.itemKey"
        />
      </el-select>

      <el-input v-model="listQuery.jobNumber" placeholder="设备MAC" style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >

      <el-table-column label="序号" align="center" width="50">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备mac" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.devCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="窗口" align="center">
        <template slot-scope="{row}">
          <!-- <span>{{ row.hallName }}</span> -->
          <span>{{ row.windowName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用" width="60" align="center">
        <template slot-scope="{row}">
          <span>{{ row.devStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号" width="60" align="center">
        <template slot-scope="{row}">
          <span>{{ row.devType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分辨率" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resolutionRatio }}</span>
        </template>
      </el-table-column>
      <el-table-column label="尺寸" width="60" align="center">
        <template slot-scope="{row}">
          <span>{{ row.devSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="ip地址" width="110" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="在线" width="60" align="center">
        <template slot-scope="{row}">
          <span>{{ row.online }}</span>
        </template>
      </el-table-column>
      <!--设备使用状态  0 带待审核，激活  1正常   2禁用  3报修 4报废 -->
      <el-table-column label="操作" align="left" width="350" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-row style="padding-bottom:5px">
            <el-button v-show="1" size="small" type="primary" @click="handleUpdate(row,$index)">
              编辑
            </el-button>
            <el-button v-show="row.devStatus!='0' && row.devStatus!='2' && row.devStatus!='3' && row.devStatus!='4' " size="small " type="danger" @click="handleChange(row,$index,0)">
              禁用
            </el-button>
            <el-button v-show="row.devStatus=='0'" size="small " type="success" @click="handleChange(row,$index,1)">
              激活
            </el-button>
            <el-button v-show="row.devStatus!='0' && row.devStatus!='3' && row.devStatus!='4' " size="small " type="warning" @click="handleChange(row,$index,2)">
              报修
            </el-button>

            <el-button v-show="row.devStatus!='0' && row.devStatus!='4' " size="small " type="warning" @click="handleChange(row,$index,3)">
              报废
            </el-button>

            <el-button v-show="row.devStatus!='0' && row.devStatus!='1' " size="small " type="info" @click="handleChange(row,$index,4)">
              恢复
            </el-button>

            <el-button v-show="row.devStatus=='1'" size="small " type="info" @click="handleView(row,$index)">
              远程
            </el-button>

          </el-row>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="400px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="绑定窗口" prop="title">
              <!-- <el-input v-model="temp.windowName" /> -->
              <el-cascader
                v-model="temp.windowId"
                style="width:100%"
                :options="options"
                :props="{ expandTrigger: 'hover',value:'id',label:'lable',emitPath:false}"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="分辨率" prop="title">
              <el-input v-model="temp.resolutionRatio" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="型号" prop="type">
              <el-select v-model="temp.devType" class="filter-item" placeholder="请选择">
                <el-option value="x1" />
                <el-option value="x2" />
                <el-option value="x3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="尺寸" prop="title">
              <el-input v-model="temp.devSize" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrgTree, pageQuareApi, editApi, getByIdApi, addApi, DeleteApi, remoteViewApi, devOperationApi } from '@/api/sysmanage'
import { getDicApi } from '@/api/public'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
        value:'',
        // getTypeList:[],
        // OrgList:[],
        devStatusList:[],
        devTypeList:[],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          devType: '',
          devStatus: '',
          online:''
        },
        temp:  {
          "devName": "",
          "devSize": "",
          "devStatus": "",
          "devType": "",
          "id": '',
          "resolutionRatio": "",
          "windowId": ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false,
        updateObj:{
          index:'',
          data:[]
        },
        options:[]
      }
    },
    created() {
      this.getList()
      getDicApi({dictCode:"dev_type"}).then(
        res=>{
          this.devTypeList= res.data
        }
      )
      getDicApi({dictCode:"dev_status"}).then(
        res=>{
          this.devStatusList= res.data
        }
      )
     getOrgTree().then(response => {
        const { data } = response
        this.options=this.digui(data)
        console.log('TCL: getData -> this.dataList', this.options)

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    methods: {
      // 递归增加是否leaf（窗口节点才是最后一级）
      digui(arr){
        let _that=this
        if(!arr){
          return null
        }
        return arr.map((ele,index)=>{
          if(ele.type!='window'){
            ele.id=ele.type+ele.id
          }
          if(ele.type!='window'&&!(ele.children)){
            ele.children=[]
            ele.id=ele.type+ele.id
          }else{
            ele.children=_that.digui(ele.children)
          }
          
          return ele
        })
      },
     
      getList() {
        this.listLoading = true
        pageQuareApi (this.listQuery,'device').then(response => {
          this.list = response.data.list
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      /**
       * 设备操作(激活，禁用，报修，报废,恢复正常使用)
       * @param row
       * @param index
       * @param status
       */
      handleChange(row,index,action){

        const obj={
          "actionType": action,
          "id": row.id,
          "remark": ""
        }
        devOperationApi(obj).then(res=>{
          const {code,id,message}=res

          if(code==="200"){
            this.$message({
              message: message,
              type: 'success',
            })
            row.devStatus=(status-0+1)
          }else{
            this.$message({
              message: message,
              type: 'success',
            })
          }
        })
      },
      handleView(row,index){
        const {id}=row
        remoteViewApi({id}).then(res=>{
          const {code,message}=res
          if(code==='200'){
            this.$message({
              message: message,
              type: 'success',
            })
          }else{
            this.$message({
              message: message,
              type: 'warning',
            })
          }

        })
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {//重置修改模态框
        this.temp = {
          "devName": "",
          "devSize": "",
          "devStatus": "",
          "devType": "",
          "id": '',
          "resolutionRatio": "",
          "windowId": ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // createData() {
      //   this.$refs['dataForm'].validate((valid) => {
      //     console.log("TCL: createData -> this.temp.windowId", this.temp.windowId)
      //     let _data= {
      //        "devName": "",
      //       "devSize": "",
      //       "devStatus": "",
      //       "devType": "",
      //       "id": '',
      //       "resolutionRatio": "",
      //       "windowId": ''
      //     }
      //     if (valid=true) {
      //       addApi(_data,'device').then((res) => {
      //         if(res.code==='200'){
      //           this.$message({
      //             message: res.message,
      //             type: 'success',
      //           })
      //           this.dialogFormVisible = false
      //           this.list.unshift(res.data)
      //           //  this.handleFilter()//刷新重新请求
      //         }
      //       })
      //     }
      //   })
      // },
      handleUpdate(row,index) {
        this.resetTemp()
        getByIdApi({id:row.id},'device').then(res=>{
        console.log("TCL: handleUpdate -> res", res)
          this.temp = res.data
          const {data}=res
          this.temp = {
          "devName":data.devName,
          "devSize": data.devSize,
          "devStatus": data.devStatus,
          "devType": data.devType,
          "id": data.id,
          "resolutionRatio": data.resolutionRatio,
          "windowId": data.windowId,
        }
        })
        //保存修改的行数据，索引
        this.updateObj={
          index:index,
          data:row
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid=true) {
          console.log("TCL: updateData -> this.temp.windowId", this.temp.windowId)

            const tempData = Object.assign({}, this.temp)
            editApi(tempData,'device').then((res) => {
              this.dialogFormVisible = false
              if(res.code==='200'){
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                const {index,data}=this.updateObj
                const row=Object.assign(data, this.temp)
                console.log("TCL: updateData -> row", row)
                this.list.splice(index,1,row)
              }else{
                this.$message({
                  message: res.message||'修改失败',
                  type: 'error'
                })
              }

            })
          }
        })
      },
      handleDelete(row,index) {
        this.$confirm('此操作不可逆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(res => {
          DeleteApi({id:row.id},'device').then(res=>{
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.list.splice(index,1)
          }).catch(err=>{
            this.$message({
              message:err.message,
              type: 'error'
            })
          })

          // row.status = status
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }

    }
  }
</script>
